package com.wantup.springboot.boot.quartz.demo1;

import org.quartz.JobDetail;
import org.quartz.Trigger;
import org.springframework.beans.factory.config.MethodInvokingFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;

/**
 * @author Zhaoluowei
 * @version 1.0
 * @date 2018/11/9 11:24
 */
//@Configuration
public class QuartzConfiguration {

    /**
     * 任务一
     * @param firstJob
     * @return
     */
    @Bean("firstJobDetail")
    public MethodInvokingJobDetailFactoryBean firstJobDetail(FirstJob firstJob){
        MethodInvokingJobDetailFactoryBean jobDetailFactoryBean = new MethodInvokingJobDetailFactoryBean();
        jobDetailFactoryBean.setConcurrent(false);
        jobDetailFactoryBean.setTargetObject(firstJob);
        jobDetailFactoryBean.setTargetMethod("firstJobTask");
        return jobDetailFactoryBean;
    }

    /**
     * 触发器 一
     * @param firstJobDetail
     * @return
     */
    @Bean("firstTrigger")
    public SimpleTriggerFactoryBean firstTrigger(JobDetail firstJobDetail){
        SimpleTriggerFactoryBean triggerFactoryBean = new SimpleTriggerFactoryBean();
        triggerFactoryBean.setJobDetail(firstJobDetail);
        //设置任务启动时间
        triggerFactoryBean.setStartDelay(0L);

        //设置时间间隔
        triggerFactoryBean.setRepeatInterval(1000L);
        return triggerFactoryBean;
    }


    /**
     * 配置任务2
     * @param secondJob
     * @return
     */
    @Bean("secondJobDetail")
    public MethodInvokingJobDetailFactoryBean secondJobDetail(SecondJob secondJob){
            MethodInvokingJobDetailFactoryBean jobDetailFactoryBean = new MethodInvokingJobDetailFactoryBean();
            jobDetailFactoryBean.setConcurrent(false);
            jobDetailFactoryBean.setTargetObject(secondJob);
            jobDetailFactoryBean.setTargetMethod("secondJobTask");

            return jobDetailFactoryBean;
    }

    /**
     * 第二个任务的触发器
     * @param secondJobDetail
     * @return
     */
    @Bean("secondTrigger")
    public CronTriggerFactoryBean secondTrigger(JobDetail secondJobDetail){
        CronTriggerFactoryBean triggerFactoryBean = new CronTriggerFactoryBean();
        triggerFactoryBean.setJobDetail(secondJobDetail);
        //cron 表达式
        triggerFactoryBean.setCronExpression("0/2 * * * * ?");
        return triggerFactoryBean;
    }

    @Bean("scheduler")
    public SchedulerFactoryBean schedulerFactory(Trigger firstTrigger,Trigger secondTrigger){
        SchedulerFactoryBean bean = new SchedulerFactoryBean();

        //相当于是两个线程 同时进行
        bean.setStartupDelay(1);
        bean.setTriggers(firstTrigger,secondTrigger);
        return bean;
    }


}

